package com.futu.common.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 获取缓存
    public String get(String key) {
        try {
            return stringRedisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            // 捕获反序列化异常，自动删除损坏的key并打印日志
            System.err.println("Redis缓存读取异常，将自动删除损坏的key: " + key);
            System.err.println("异常信息: " + e.getMessage());
            stringRedisTemplate.delete(key);
            return null;
        }
    }

    // 设置缓存（带过期时间，单位：秒）
    public void set(String key, String value, long timeout) {
        stringRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    // 删除缓存
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }
    
    // 检查key是否存在
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
    }
    
    // 打印所有键（用于调试）
    public void printAllKeys(String pattern) {
        try {
            System.out.println("===== Redis Keys (" + pattern + ") =====");
            for (String key : stringRedisTemplate.keys(pattern)) {
                System.out.println(key + " => " + get(key));
            }
            System.out.println("==========================");
        } catch (Exception e) {
            System.err.println("获取Redis键出错: " + e.getMessage());
        }
    }
    
    // 删除所有匹配指定模式的键
    public void deleteKeysWithPattern(String pattern) {
        try {
            System.out.println("删除所有匹配模式的键: " + pattern);
            stringRedisTemplate.delete(stringRedisTemplate.keys(pattern));
            System.out.println("删除完成");
        } catch (Exception e) {
            System.err.println("删除Redis键出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
